package daoImp;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;


import util.DateUtil;

import dao.TrendFrequencyDAO;

public class TrendFrequencyDAOImpl implements TrendFrequencyDAO{
	private static TrendFrequencyDAOImpl uniqueInstance = new TrendFrequencyDAOImpl();
	private ConnectionPool pool = ConnectionPool.getInstance();
	
	public static TrendFrequencyDAOImpl getInstance() {
		return uniqueInstance;
	}

	private TrendFrequencyDAOImpl() {
	}

	public int[] getRecentFrequency(String trend, Date date, int offset) {
		int[] frequencies = new int[offset];
		String[] dateStrs = DateUtil.getDateStrs(date, offset);
		
		String sql = null;
		Statement stmt = null;
		Connection connection;
		try {
			connection = pool.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
			return frequencies;
		}
		try {
			connection.setAutoCommit(false);
			stmt = connection.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		for(int i = 0; i < dateStrs.length; i++){
			try {
				String dateStr = dateStrs[i];
				sql = "select frequency from trendfrequency where trend = '" + trend + "' and date = '" + dateStr + "';";
				ResultSet rs = stmt.executeQuery(sql);
				boolean find = false;
				while (rs.next()) {
					find = true;
					int frequency = rs.getInt(1);
					frequencies[i] = frequency;
				}
				if(!find)
					frequencies[i] = 0;
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		try {
			stmt.close();
			connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			pool.returnConnection(connection);
		}
		return frequencies;
	}
	
	public static void main(String[] args) {
		 try {
				ConnectionPool.getInstance().createPool();
			} catch (Exception e) {
				e.printStackTrace();
			}
		 int[] a = TrendFrequencyDAOImpl.getInstance().getRecentFrequency("Europa", new Date(), 5);
		 for(Integer b  : a)
			 System.out.println(b);
	}
}
